package servlets;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import webservices.helper.Helper;
import control.ControlService;

/**
 * Servlet implementation class CourseManageServlet
 */
public class CourseQueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response){
		try{
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e){}
		
		String userID = (String)request.getSession().getAttribute("userID");
		String requestXML = "<param name='userID' value='" + (userID == null ? 1 : userID) + "' />";
		
		String responseXML = new ControlService().Call("CourseQuery", requestXML);
		
		try {
			NodeList responseList = Helper.getResponse(responseXML);
			
			String status = ((Element)responseList.item(0)).getAttribute("name");
			String json = "";
			
			if ("success".equals(status)){
				json = "[";
				for (int i = 1; i < responseList.getLength(); i++) {
					Element course = (Element)responseList.item(i);
					
					if ( i > 1 ){
						json += ",";
					}
					
					json += "{courseID: '" + course.getElementsByTagName("courseID").item(0).getTextContent() + "',";
					json += "name: '" + course.getElementsByTagName("name").item(0).getTextContent() + "',";
					json += "description: '" + course.getElementsByTagName("description").item(0).getTextContent() + "',";
					json += "favourite: " + course.getElementsByTagName("favourite").item(0).getTextContent() + ",";
					json += "teacher: '" + course.getElementsByTagName("teacher").item(0).getTextContent() + "'}";
				}
				json += "]";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(json);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
